package com.rzjm.api.netty.water.business.inhandler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.rzjm.api.entity.DeviceWater;
import com.rzjm.api.netty.water.NettyUtil;
import com.rzjm.api.netty.water.entity.ReceiveData;
import com.rzjm.api.service.IDeviceWaterMessagesService;
import com.rzjm.api.service.IDeviceWaterService;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Optional;

import static com.rzjm.api.netty.water.constant.SendRtEnum.*;
import static com.rzjm.api.util.DateUtils.localDateTimeStartToSecond;

/**
 *  广告灯控制
 * @author Mr.Zhou
 * @Description:
 * @date 2025/3/17 9:27
 */
@Component
public class Receive5InHandler implements InHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(Receive5InHandler.class);
    @Autowired
    private IDeviceWaterService devicesService;
    @Autowired
    private IDeviceWaterMessagesService deviceMessagesService;


    @Override
    public void handler(ChannelHandlerContext ctx, ReceiveData receiveData) {
        //保存Channel
        NettyUtil.addChannel(ctx, receiveData.getId());
        // 保存上报数据日志
        Optional.ofNullable(getMessage(receiveData))
                .ifPresent(message -> deviceMessagesService.save(message));

        DeviceWater deviceWater = devicesService.findById(receiveData.getId());
        //回复消息
        String replyData = requestData(deviceWater, receiveData);
        if (StrUtil.isNotEmpty(replyData)) {
            reply(replyData, receiveData.getId());
        }
    }

    /**
     * 广告灯控制
     * @param deviceWater
     * @param receiveData
     * @return
     */
    private String requestData(DeviceWater deviceWater, ReceiveData receiveData) {
//        DeviceWater device = devicesService.findById(id);
//        if (device == null) {
//            return "{\"rt\":5,\"v1\":4}";
//        }
        String replyData;
        // 当日开始时间的总秒数
        long startSecond = localDateTimeStartToSecond();
        JSONObject obj = JSONUtil.createObj();

        obj = JSONUtil.createObj();
        obj.set("rt", SEND_RT_99.getRt());
        obj.set("v1", receiveData.getV1());
        replyData = JSONUtil.toJsonStr(obj);
        return replyData;
    }

}
